import { useMessage } from 'naive-ui';
import statusCode from '../api/statusCode';
import router from '../router';

type StatusCodeShape = typeof statusCode
type StatusCodeKey = keyof StatusCodeShape
type StatusCodeValue = StatusCodeShape[StatusCodeKey]

type FailedStatusCode = Exclude<StatusCodeValue, StatusCodeShape['SUCCESS']>
type Result<R> = { status: StatusCodeShape['SUCCESS']; data: R } |
{ status: FailedStatusCode; data: null }

const handleNoToken = (messageRef = useMessage()): void => {
  messageRef.error('还没登录，请先登录', {
    duration: 1200,
    onAfterLeave: () => router.push({
      name: 'login',
      query: { redirect: router.currentRoute.value.fullPath }
    })
  });
};

const handleResponse = <R>(resp: Response): Promise<Result<R>> => {
  if (resp.ok) {
    return resp.json() as Promise<Result<R>>;
  } else {
    throw new TypeError(resp.statusText);
  }
};

const listAllError = (errors: Error[][], messageRef = useMessage()): void => {
  errors.forEach(fieldErrs => {
    if (fieldErrs instanceof Array) {
      fieldErrs.forEach(err => messageRef.error(err.message));
    }
  });
};


export type { Result }

export {

  handleNoToken,
  handleResponse,

  listAllError
}
